<script setup lang="ts">
import MarkdownIt from 'markdown-it';
import {onMounted, watch} from "vue";

const props = defineProps({
  markdownText: {
    type: String,
  }
})
const list = ref([])
const parseMarkdown = () => {
  const md = new MarkdownIt();
  // 去掉分割线
  const regex = /^\s*([-*_])\s*\1{2,}\s*$/gm;
  const html = md.render(props.markdownText.replace(regex, ''));
  list.value = splitByHeadings(html);
}
// 按照标题分割出多个卡片
const splitByHeadings = (html: string) => {
  const parser = new DOMParser();
  const doc = parser.parseFromString(`<div id="root" class="xx">${html}</div>`, 'text/html');
  const root = doc.getElementById('root');
  let currentCard = {content: '', level: 0, title: '', min: false};
  const cards = [];
  Array.from(root.childNodes).forEach((node: any) => {
    // 按照h标签分割
    if (node.nodeType === 1 && /^H[1-6]$/i.test(node.tagName)) {
      const level = parseInt(node.tagName.substring(1));
      if (currentCard.content) {
        cards.push({...currentCard});
      }
      currentCard = {
        content: node.outerHTML,
        level,
        title: node.textContent,
        min: false
      };
      // currentCard.content = "<div class='title-wrapper'><img src='"+getIcon(currentCard.title)+"' class='h3-icon'/>"+currentCard.content+"</div>";
    }
    currentCard.content += node.outerHTML || node.textContent;
  });
  if (currentCard.content) {

    // const reg =
    // 被[ ] 包裹的部分，按照可操作卡片处理
    if (isWrappedInBrackets(currentCard.title)) {
      // 匹配url的正则
      const urlPattern = /https?:\/\/[^\s<]+/;
      // 匹配子标题的正则
      const titlePattern = /<strong>([\s\S]*?)<\/strong>/g;
      // 匹配说明部分的正则
      const ulPattern = /<ul>([\s\S]*?)<\/ul>/g;
      // 匹配按钮部分的正则
      const btnPattern = /\s*((?:购票链接|详情介绍)\[[^\]]+])/g;
      // 匹配被[ ]包裹内容的正则
      const textPattern = /\[([^\]]*)]/;

      const match = currentCard.content.match(urlPattern);
      if (match && match[0]) {
        const subtitle = currentCard.content.match(titlePattern);
        const ul = currentCard.content.match(ulPattern);
        const btn = currentCard.content.match(btnPattern);
        let content = `<img src="${match[0]}" alt=""/>`;
        if (subtitle) {
          // 说明部分
          content += `<h3 style="margin-top: 4px">${currentCard.title.replace('[', '').replace(']', '')}</h3>`
          // 子标题部分
          for (let i = 0; i < subtitle.length; i++) {
            content += subtitle[i].replace('[', '').replace(']', '') + '<div style="margin-top: 6px"/>';
          }
        }
        // 说明部分
        if (ul) {
          const ulDom = ul[0].replace(btnPattern, '').replaceAll('[', '').replaceAll(']', '');
          const tempDiv = document.createElement('div');
          tempDiv.innerHTML = ulDom;
          const listItems = tempDiv.querySelectorAll('li');
          listItems.forEach(li => {
            const text = li.textContent;
            const colonIndex = text.indexOf('：');

            if (colonIndex !== -1) {
              // 分割冒号前后的文本
              const beforeColon = text.substring(0, colonIndex + 1);
              const afterColon = text.substring(colonIndex + 1);

              // 创建带样式的 HTML
              li.innerHTML = `${beforeColon}<span style="color: #FF7F00;">${afterColon}</span>`;
            }
          });
          content += tempDiv.innerHTML;
        }
        // 按钮部分
        if (btn && btn.length > 0) {
          content += '<div class = "btn-container">'
          for (let i = 0; i < btn.length; i++) {
            content += `<a class="a-btn" href="${btn[i].match(textPattern)[0]
                .replaceAll('[', '')
                .replaceAll(']', '')}">${btn[i].replace(textPattern, '')}</a>`
          }
          content += '</div>'
        }
        currentCard.content = content;
        currentCard.min = true;
      }
    }
    cards.push(currentCard);
  }
  return cards;
}
onMounted(() => parseMarkdown());

watch(() => props.markdownText, () => {
  parseMarkdown();
})
const  isWrappedInBrackets = (text: string) => {
  if (typeof text !== 'string') return false;
  const len = text.length;
  if (len < 2) return false;
  return text.charAt(0) === '[' && text.charAt(len - 1) === ']';
}
const getIcon = (title: string) => {
  if (title.indexOf('上午行程') >= 0 || title.indexOf('中午安排') >= 0 || title.indexOf('下午行程') >= 0) {
    return '/morning.png'
  }
  if (title.indexOf('傍晚') >= 0) {
    return '/evening.png'
  }
  if (title.indexOf('亮点') >= 0) {
    return '/highlight.png'
  }
  if (title.indexOf('橘子洲') >= 0) {
    return '/juzizhou.png'
  }
  if (title.indexOf('游玩路线') >= 0) {
    return '/route.png'
  }
  if (title.indexOf('拍照') >= 0) {
    return '/photograph.png'
  }
  if (title.indexOf('小贴士') >= 0) {
    return '/notice.png'
  }
  if (title.indexOf('注意') >= 0||title.indexOf('备注') >= 0) {
    return '/notice.png'
  }
  if (title.indexOf('票价') >= 0 || title.indexOf('费用') >= 0) {
    return '/ticket.png'
  }
  if (title.indexOf('文化') >= 0) {
    return '/culture.png'
  }
  if (title.indexOf('餐厅') >= 0) {
    return '/restaurant.png'
  }
  return '/default.png'
}
</script>

<template>
  <div class="markdown-cards">
    <div v-for="(card, index) in list" :key="index" class="card" :style="{width: card.min ? '65vw':''}">
      <div v-html="card.content"></div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.markdown-cards {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.card {
  display: inline-block;
  border: 1px solid #eaeaea;
  border-radius: 8px;
  padding: 1rem;
  background: #fff;
  word-break: break-all;
  word-wrap: break-word;
}

:deep() table {
  border-collapse: collapse;
  width: 100%;
  margin: 1rem 0;
}

:deep() th, :deep() td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

:deep() th {
  background-color: #f2f2f2;
  font-weight: bold;
}

:deep() tr:nth-child(even) {
  background-color: #f9f9f9;
}

:deep() h3 {
  margin-bottom: 12px;
}

:deep() ul, ol {
  padding-left: 0.5em;
  padding-bottom: 0.5em;
}

:deep() li {
  color: #5e5e5e;
  padding-bottom: 0.15em;
  padding-top: 0.15em;
}

:deep() li strong {
  color: initial;
}

:deep() img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

:deep() .a-btn {
  display: inline-block;
  background-color: #FF7F00;
  color: white;
  padding: 5px 10px;
  text-align: center;
  text-decoration: none;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-left: 6px;
}
:deep() a{
  display: inline-block;
  background-color: #FF7F00;
  color: white;
  padding: 5px 10px;
  text-align: center;
  text-decoration: none;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-left: 6px;
}

/* 悬停效果 */
:deep() .a-btn:hover {
  background-color: #FF7F00;
}

/* 点击时效果 */
:deep() .a-btn:active {
  background-color: #F3974B;
  transform: translateY(1px); /* 轻微下移，模拟按下的效果 */
}

:deep() .btn-container {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
:deep() .title-wrapper {
  display: flex;
}
:deep() .h3-icon {
  width: 12px;
  height: 12px;
  margin-right: 10px;
  margin-top: 6px;
}
:deep() .li-icon {
  display: inline-block;
  vertical-align: middle;
  margin-right: 6px;
  width: 20px;
  height: 20px;
}
</style>
